package org.ysu.service.impl;

import org.springframework.stereotype.Service;
import org.ysu.dto.RegionData;
import org.ysu.dto.RegionDataforBigDecimal;
import org.ysu.service.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Resource
    ProvincesService provincesService;
    @Resource
    CitiesService citiesService;
    @Resource
    AreasService areasService;
    @Resource
    FamilyService familyService;
    @Resource
    InterviewService interviewService;
    public List<RegionData> getRegionCount(String regionCode) {
        List<RegionData> result = new ArrayList<>();
        long code = Long.parseLong(regionCode);
        String level = getRegionLevel(code);

        List<Long> regionCodes = new ArrayList<>();
        if ("全国".equals(level)) {
            regionCodes = provincesService.getAllCodes();
        } else if ("省级".equals(level)) {
            regionCodes = citiesService.getCodesByProvinceCode(code);
        } else if ("市级".equals(level)) {
            regionCodes = areasService.getCodesByCityCode(code);
        }

        int count=0;
        for (Long rId : regionCodes) {
            String name = getRegionName(level, rId);
            count = familyService.count(rId);
            result.add(new RegionData(name, count));
        }

        return result;
    }

    public List<RegionDataforBigDecimal> getRegionAvgIncome(String regionCode){
        List<RegionDataforBigDecimal> result = new ArrayList<>();
        long code = Long.parseLong(regionCode);
        String level = getRegionLevel(code);


        List<Long> regionCodes = new ArrayList<>();
        if ("全国".equals(level)) {
            regionCodes = provincesService.getAllCodes();
        } else if ("省级".equals(level)) {
            regionCodes = citiesService.getCodesByProvinceCode(code);
        } else if ("市级".equals(level)) {
            regionCodes = areasService.getCodesByCityCode(code);
        }


        for (Long rId : regionCodes) {
            String name = getRegionName(level, rId);
            BigDecimal count = interviewService.getAvgIncomeByRegionId(rId);
            result.add(new RegionDataforBigDecimal(name, count));
        }

        return result;
    }

    private String getRegionLevel(long code) {
        if (code == 0) return "全国";
        if (code < 100) return "省级";
        return "市级";
    }

    private String getRegionName(String level, Long rId) {
        if ("全国".equals(level)) {
            return provincesService.getNameById(rId);
        } else if ("省级".equals(level)) {
            return citiesService.getNameById(rId);
        } else if ("市级".equals(level)) {
            return areasService.getNameById(rId);
        }
        return "未知";
    }
}

